//
//  WBMainViewController.swift
//  weibo
//
//  Created by 李海超 on 2017/5/21.
//  Copyright © 2017年 lihaichao. All rights reserved.
//


















import UIKit

class WBMainViewController: UITabBarController,UITabBarControllerDelegate {
    
    //使用oc的构造方法返回实例时，应在变量后标明类型，因为oc构造器返回instancetype的可选类型
    private lazy var composeBtn:UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChidController()
        
        setupComposeButton()
        
        
        delegate = self
    }
    
    
    
    
    //设置竖屏，这样子类也会都是竖屏，所以写在UITabBarController下，一般视频播放都是model出来的
    //这样可以重新设置
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    
    /**
        创建UI
     */
    private func setupChidController(){
        //从沙盒中加载
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        
        let jsonpath = (docDir as NSString).appendingPathComponent("main.json")
        
        var data = NSData(contentsOfFile: jsonpath)
        
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        
        //从Bundle中加载
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]]
        else {
            return
        }
        
        
        
        /*let array = [
            ["clsname":"WBHomeViewController","title":"首页","imageName":"home","visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜关注一些人，回这里看看有什么惊喜"]],
            ["clsname":"WBMessageViewController","title":"消息","imageName":"message_center","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
            [:],
            ["clsname":"WBDiscoverViewController","title":"发现","imageName":"discover","visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
            ["clsname":"WBprofileViewController","title":"我","imageName":"profile","visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
        ]
        
        
        //(array as NSArray).write(toFile: "/Users/chaoge/Desktop/demo.plist", atomically: true)
        
        //将数组输出为json
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        
        (data as NSData).write(toFile: "/Users/chaoge/Desktop/demo.json", atomically: true)
        
        */
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
        
        
    }
    /**
     根据字典返回自控制器
     
     - parameter dict: 子控制器的属性字典
     
     - returns: 创建好的子控制器
     */
    private func controller(dict:[String:Any])->UIViewController{
        
        guard let clsName = dict["clsname"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls =  NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
            let visitorDict = dict["visitorInfo"] as? [String:String]
            else {
                return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        //1.
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        //2.
        //tabBar.tintColor = UIColor.orange
        
        //设置visitor的信息字典
        vc.visitorDict = visitorDict
        
        let nav = WBNavViewController(rootViewController: vc)
        
        
        return nav
    }
    
    
    /**
     tabbarController代理方法，让中间按钮失效
     
     - parameter tabBarController: tabBarController
     - parameter viewController:   目标控制器
     
     - returns: 是否切换到目标控制器
     */
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        
       return !viewController.isMember(of: UIViewController.self)
        
    }
    

    /**
     *  设置中间的撰写按钮的位置
     */
    private func setupComposeButton(){
        
        tabBar.addSubview(composeBtn)
        
        let count = childViewControllers.count
        //减一是为了增大撰写按钮的宽度，避免用户点到两个item之间的容错点
        let w = tabBar.bounds.width / CGFloat(count)
        //撰写按钮的frame等于tabbar的bounds从左到右和从右到左各缩紧2个w
        composeBtn.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        
        composeBtn.addTarget(self, action: #selector(composeBtnClick), for: .touchUpInside)
        
        
    }
    
    
    /**
     *  撰写按钮的监听方法，使用model跳转检测横竖屏
     */
    
    @objc private func composeBtnClick(){
    
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor.red
        
        let nav = UINavigationController(rootViewController: vc)
        
        present(nav, animated: true, completion: nil)
        
        
        print("撰写微博")
    }
    
}






















